package edu.upb.acs.jobsmaps.database.json;

import android.util.Log;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import edu.upb.acs.jobsmaps.entity.Company;
import edu.upb.acs.jobsmaps.entity.Job;

import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dani on 1/16/14.
 */
public class CompanyJsonParser {
	private static final String TAG = CompanyJsonParser.class.getName();

    public static List<Company> parse(String fileName) {
        BufferedReader input = null;
        try {
            input = new BufferedReader(new FileReader(fileName));
            StringBuilder contents = new StringBuilder();

            //use buffering, reading one line at a time
            //FileReader always assumes default encoding is OK!
            try {
                String line = null; //not declared within while loop
                while ((line = input.readLine()) != null) {
                    contents.append(line);
                    contents.append(System.getProperty("line.separator"));
                }
            } catch (IOException e) {
				Log.e(TAG, "Can not import content", e);
				return null;
            } finally {
                try {
                    input.close();
                } catch (IOException e) {
					Log.e(TAG, "Can not import content", e);
					return null;
                }
            }

            JsonParser jsonParser = new JsonParser();
            JsonObject mappings = (JsonObject) jsonParser.parse(contents.toString());
            JsonArray jsonArr = mappings.getAsJsonArray("companies");

			Type listType = new TypeToken<List<Job>>() {
			}.getType();

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

			List<Company> companies = new ArrayList<>()
;			for (int i = 0; i < jsonArr.size(); i++) {
				JsonObject companyJson = jsonArr.get(i).getAsJsonObject();
				JsonElement jobsJson = companyJson.remove("jobs");
				Company company = gson.fromJson(companyJson, Company.class);
				company.setAverageRating(0d);

				List<Job> jobs = gson.fromJson(jobsJson, listType);
				for (Job job : jobs) {
					job.setActive(true);
				}
				company.setJobs(jobs);

				companies.add(company);
			}

            System.out.println(companies);
            return companies;
        } catch (FileNotFoundException e) {
			Log.e(TAG, "Can not import content", e);
			return null;
        }
    }

}